
const fs = require('fs');
const chalk = require('chalk');
const config = require('./config');
const path = require('path');
const uploadTest = require('./uploadHtmlFupload');
const uploadRelease = require('./uploadHtmlXingShi');
// 获取所有html文件
function getFiles(dir,fileList){
  const files = fs.readdirSync(dir);
  files.forEach(file=>{
    const filePath = path.join(dir,file);
    if(fs.lstatSync(filePath).isDirectory()){
      getFiles(filePath,fileList);
    }else if(file.search(/\.html$/)>=0){
      fileList.push(filePath);
    }
  });
}
//设置charset utf8
async function setCharset(fileList){
  const fileListPromise = fileList.map(file=>{
    return new Promise(resolve=>{
      fs.readFile(file,{encoding:'utf-8'},(err,data)=>{
        if(err) throw err;
        fs.writeFile(
          file,
          data.replace(/\<script/g,'<script charset="UTF-8"')
              .replace(/\<link/g,'<link charset="UTF-8"')
              .replace(/t\=e.createElement\(\"script\"\)\;/g,'t=e.createElement("script");t.charset="UTF-8";'),
          (err)=>{
          if(err) throw err;
          resolve();
        });
      });
    });
  });

  return Promise.all(fileListPromise);
}
module.exports = async function(){
  console.log(chalk.black.bgYellow(`${config.testEnv?'[测试]':'[正式]'}`),chalk.yellow(`正在上传HTML...`));
  const fileList = [];
  getFiles(config.projectDist,fileList);
  await setCharset(fileList);
  if(config.testEnv) {
    //测试地址
    for(let file of fileList){
      await uploadTest(file);
    }
  } else {
    //正式地址
    for(let file of fileList){
      await uploadRelease(file);
    }
  }
  console.log(chalk.green(`文件夹："${path.relative(path.join(config.projectPath,'..'),config.projectDist)}"内所有HTML文件上传完成`),'\n');
}